﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Media.Animation;
using EZMemoLib;
using Microsoft.Windows.Controls;
using Remember.WPF.Views;

namespace Remember.WPF.Pages
{
    /// <summary>
    /// Interaction logic for PlayerPage.xaml
    /// </summary>
    public partial class PlayerPage : Page
    {
        public event EventHandler OnFinished;
        DoubleAnimation animFadeIn = new DoubleAnimation();
        DoubleAnimation animFadeOut = new DoubleAnimation();
        public PlayerPage()
        {
            InitializeComponent();

            var margin = btnAlmost.Margin;
            btnStart.HorizontalAlignment = btnAlmost.HorizontalAlignment;
            btnStart.Margin = margin;
            btnStart.Focus();

            btnEnd.HorizontalAlignment = btnAlmost.HorizontalAlignment;
            btnEnd.Margin = margin;
            btnEnd.Visibility = System.Windows.Visibility.Collapsed;

            btnCheckAnswer.HorizontalAlignment = btnAlmost.HorizontalAlignment;
            btnCheckAnswer.Margin = margin;

            WaittingAnswer(false);
            OptionStart(false);

            animFadeIn = new DoubleAnimation();
            animFadeIn.From = 0;
            animFadeIn.To = 1;
            animFadeIn.Duration = new Duration(TimeSpan.FromMilliseconds(1600));
            this.BeginAnimation(OpacityProperty, animFadeIn);

            animFadeOut = new DoubleAnimation();
            animFadeOut.From = 1;
            animFadeOut.To = 0;
            animFadeOut.Duration = new Duration(TimeSpan.FromMilliseconds(500));

            this._ItemCard.OnGoEdit += new EventHandler(_ItemCard_OnGoEdit);
        }

        long _BookID;

        MemoCategory bookInfo = null;
        public PlayerPage( long bookID) :this()
        {
            _BookID = bookID;
            this._ItemCard.BookID = bookID;

            string loginID = (Context.Login != null) ? Context.Login.LoginID : string.Empty;
            player = Player.Instance( loginID, _BookID);

            ShowBookInformation();



            player.EstimateTodayList();
            ShowStat();
        }

        void _ItemCard_OnFoundVoice(object sender, EventArgs e)
        {
            
        }

        void _ItemCard_OnGoEdit(object sender, EventArgs e)
        {
            //ChildWindow cw = new ChildWindow();
            //cw.Content = new LoginAdd();
            //cw.Show();

            
            var item = sender as MemoItem ;
            if ( item != null )
            {
                var itemEditPage = new ItemEditPage();
                itemEditPage.EditItem = item;
                //itemEditPage.Show();
                itemEditPage.ShowDialog ();
            }
        }

        bool IsCheckAnswer = false;

        void ShowBookInformation()
        { 
            bookInfo = BookBusiness.Instance().GetCategory ( _BookID );
            if (bookInfo != null)
            {
                this.statusBar1.uiBookName.Text = bookInfo.CategoryName;

                uiStartBoard.Visibility = System.Windows.Visibility.Visible;
                uiStartBoard.Text = bookInfo.CategoryName;
            }

        }

        void ShowStat()
        {
            this.statusBar1.uiBookName.Text = bookInfo.CategoryName;

            this.statusBar1.uiTotal.Text = string.Format("{0} / {1}", player.TotalCursor  , player.Total );
            this.statusBar1.uiRepetition.Text = string.Format("{0} / {1}", player.RepeCursor, player.RepetitionToday);
            this.statusBar1.uiNew.Text = string.Format("{0} / {1}", player.NewCursor , player.NewToday );
            this.statusBar1.uiDrills.Text = string.Format("{0}", player.DrillToday );


            this.statusBar1.uiDiff.Text = "0";

            this.statusBar1.uiLatest.Text = string.Format("{0}", DateTime.Now.ToShortDateString());
            this.statusBar1.uiStart.Text = "" ;

            if (_Item != null)
            {
                if (_Item.Category != null)
                {
                    long lid = _Item.Category.Value;
                    var lesson = BookBusiness.Instance().GetLesson (  lid );
                    if (lesson != null)
                    {
                        this.statusBar1.uiLessonName.Text = lesson.CategoryName;    
                    }
                    else
                    {
                        this.statusBar1.uiLessonName.Text = "";
                        
                    }
                }

                //this.statusBar1.uiDrills.Text = "0";
                //var drilllist = player.GetDrillListFromDB();
                //if (drilllist != null)
                //{
                //    this.statusBar1.uiDrills.Text = string.Format ( "{0}", drilllist.Count);
                //}

                var history = player.GetHistoryInfo(_Item.ItemID);
                if (history != null)
                {
                    this.statusBar1.uiCurveIndex.Text = string.Format("{0}", history.CurveIndex );
                    this.statusBar1.uiDiff.Text = string.Format("{0}", history.Difficulty );
                    this.statusBar1.uiStart.Text = string.Format("{0}", history.StartDate != null ? history.StartDate.Value.ToShortDateString() : "");
                    this.statusBar1.uiLatest.Text = string.Format("{0}", history.LastDate != null?history.LastDate.Value.ToShortDateString ():"" );

                }
                else
                {
                    this.statusBar1.uiDiff.Text = "0";
                    this.statusBar1.uiCurveIndex.Text = string.Format("{0}", 0);
                    this.statusBar1.uiLatest.Text = string.Format("{0}", DateTime.Now.ToShortDateString());

                }


            }
        }

        /// <summary>
        /// this show the check button, to wait your thinking.
        /// </summary>
        /// <param name="start"></param>
        void WaittingAnswer(bool start)
        {
            if (start)
            {
                btnCheckAnswer.Visibility = System.Windows.Visibility.Visible;
                IsCheckAnswer = true;
            }
            else
            {
                btnCheckAnswer.Visibility = System.Windows.Visibility.Hidden;
                IsCheckAnswer = false;
            }
        }

        void OptionStart(bool start)
        {
            if (start)
            {
                btnAlmost.Visibility = System.Windows.Visibility.Visible;
                btnKnew.Visibility = System.Windows.Visibility.Visible;
                btnUnknow.Visibility = System.Windows.Visibility.Visible;

                this.btnKnew.Focus();
            }
            else
            {
                btnAlmost.Visibility = System.Windows.Visibility.Hidden;
                btnKnew.Visibility = System.Windows.Visibility.Hidden;
                btnUnknow.Visibility = System.Windows.Visibility.Hidden;
            }
        }

        Player player;
        MemoItem _Item;
        void Start()
        {

            _Item = player.GetStartItem( );
            ShowItemFlow();

            this.btnCheckAnswer.Focus();
            lblKeyInfo.Content = "Got Focus!";
        }

        void ShowItemFlow()
        {
            ShowStat();

            if (_Item != null)
            {
                ShowFirst();
            }
            else
            {
                ShowEndOfAll();
            }

            btnCheckAnswer.Focus();

            OptionStart(false);
        }

        void ShowFirst()
        {
            this._ItemCard.PlayItem (_Item);
            WaittingAnswer(true);

        }
        void ShowLater()
        {
            WaittingAnswer(false);

            this._ItemCard.PlayLate ();

            OptionStart(true);
        }

        void ShowEndOfAll()
        {
            _ItemCard.End();

            WaittingAnswer(false);

            btnEnd.Visibility = System.Windows.Visibility.Visible;
            
            //this.btnStart.Visibility = System.Windows.Visibility.Visible;
            //this.btnStart.Content = "Once more?";
        }

        private void btnUnknow_Click(object sender, RoutedEventArgs e)
        {
            if (_Item == null)
                return;

            player.SaveResult(_Item.ItemID, CheckResultType.DidnotKnow);

            _Item = player.GetNextItem();
            ShowItemFlow();
        }

        private void btnAlmost_Click(object sender, RoutedEventArgs e)
        {
            if (_Item == null)
                return;

            player.SaveResult(_Item.ItemID, CheckResultType.Almost);
            _Item = player.GetNextItem();
            ShowItemFlow();
        }

        private void btnKnew_Click(object sender, RoutedEventArgs e)
        {
            if (_Item == null)
                return;

            player.SaveResult(_Item.ItemID, CheckResultType.Knew);
            _Item = player.GetNextItem();
            ShowItemFlow();
        }

        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            Start();

            this.uiStartBoard.Visibility = System.Windows.Visibility.Collapsed;
            this.btnStart.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void btnEnd_Click(object sender, RoutedEventArgs e)
        {
            if (OnFinished != null)
            {
                OnFinished(this, null);
            }
        }

        private void btnCheckAnswer_Click(object sender, RoutedEventArgs e)
        {
            ShowLater();
        }

        private void Window_KeyUp(object sender, KeyEventArgs e)
        {
            e.Handled = true;

            this.lblKeyInfo.Content = e.Key.ToString();
            if (player != null && player.RepeCursor > 0)
            {
                switch (e.Key)
                {
                    case Key.Escape:

                        var rc = System.Windows.Forms.MessageBox.Show("Are you cancel this lesson?","Cancelling a lesson", System.Windows.Forms.MessageBoxButtons.YesNo );
                        if (rc == System.Windows.Forms.DialogResult.Yes )
                        {
                            ShowEndOfAll();
                        }
                        break;

                    case Key.Enter:
                    case Key.Right:

                        if (IsCheckAnswer)
                        {
                            //btnCheckAnswer_Click(sender, null);
                        }
                        else
                        {
                            //btnKnew_Click(sender, null);
                        }

                        break;
                    case Key.Left:

                        //btnUnknow_Click(sender, null);

                        break;
                    case Key.Down:

                        break;
                    case Key.Up:
                        break;

                    case Key.Space:
                        btnAlmost_Click(sender, null);
                        break;
                    default:
                        break;

                }
            }
            else
            {
                btnStart_Click(sender, null);
            }
        }

        private void Page_SizeChanged(object sender, SizeChangedEventArgs e)
        {

        }


    }
}
